﻿using System;
using System.Collections.Generic;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace PD.WorkflowLibrary
{
    /// <summary>
    /// Represents a workflow instance.
    /// </summary>
    public class WorkflowInstanceHelper
    {
        /// <summary>
        /// Gets the instance id.
        /// </summary>
        public Guid InstanceId { get; private set; }

        /// <summary>
        /// Gets a value indicating whether this <see cref="WorkflowInstanceHelper"/> is success.
        /// </summary>
        /// <value>
        /// <c>true</c> if success; otherwise, <c>false</c>.
        /// </value>
        public bool Success { get; private set; }

        /// <summary>
        /// Creates and the runs the workflow.
        /// </summary>
        /// <typeparam name="T">The System.Type of the workflow to create.</typeparam>
        /// <param name="workflowRuntime">The workflow runtime.</param>
        /// <param name="parameters">The parameters.</param>
        public void CreateAndRunWorkflow<T>(WorkflowRuntime workflowRuntime, Dictionary<string, object> parameters)
        {
            if (workflowRuntime != null && parameters != null)
            {
                WorkflowInstance workflowInstance = workflowRuntime.CreateWorkflow(typeof(T), parameters);
                this.InstanceId = workflowInstance.InstanceId;
                workflowInstance.Start();
                this.RunWorkflow(workflowRuntime, workflowInstance.InstanceId);
            }
        }

        /// <summary>
        /// Runs the specified workflow instance.
        /// </summary>
        /// <param name="workflowRuntime">The workflow runtime.</param>
        /// <param name="workflowId">The workflow id.</param>
        public void RunWorkflow(WorkflowRuntime workflowRuntime, Guid workflowId)
        {
            if (workflowRuntime != null)
            {
                ManualWorkflowSchedulerService schedulerService = workflowRuntime.GetService<ManualWorkflowSchedulerService>();
                this.Success = schedulerService.RunWorkflow(workflowId);
            }
        }
    }
}
